package stream;

import java.util.*;

/**
 * Created by dl
 */
public class ModifySourceCollectionInStream {

	public static void main(String[] args) {
		Random random = new Random();
		Map<String, Integer> m = new HashMap<>();

		System.out.println(m);

		while (true) {
			try {
				m.clear();
				for (int i = 0; i < 26; i++) {
					m.put(String.valueOf((char) ('a' + i)), random.nextInt());
				}
				m.entrySet()
						.stream()
						// 如果不sorted，会引发异常；如果sorted，则一定不会引发异常
						.sorted(Comparator.comparing(kv -> kv.getValue()))
						.limit(20)
						.forEach(wc -> m.remove(wc.getKey()));
			} catch (ConcurrentModificationException e) {
				System.out.println("caught you");
				break;
			}
		}

		System.out.println(m);
	}
}
